import { Button, Form, Input, message, Select } from 'antd'
import React, { forwardRef, useContext, useEffect, useImperativeHandle, useState } from 'react'
import { AppContext } from '@/App'
import { TStore } from '@type'
import axios from '@/http'
import { BlogContext } from '@/pages/blog/blog'
import { useLocation, useNavigate } from 'react-router-dom'

const HeaderForm: React.ForwardRefRenderFunction<{ onFill: Function }, { text: string; html: string }> = ({ text, html }, ref) => {
  const [form] = Form.useForm()
  const [, forceUpdate] = useState({})
  const {
    store: { status }
  } = useContext<TStore>(AppContext)
  // To disable submit button at the beginning.
  useEffect(() => {
    forceUpdate({})
  }, [])
  const { id } = useContext(BlogContext)
  const { pathname } = useLocation()
  const onFinish = (values: { title: string; way: string }) => {
    pathname === '/index/blog' ? updBlog(values) : addBlog(values)
    // updBlog(values)
  }
  const updBlog = (values: { title: string; way: string }) => {
    axios
      .post('/blog/update', {
        ...values,
        status,
        content: html,
        editContent: text,
        id
      })
      .then(res => {
        if (res.data.error === -1) {
          message.success('博客更新成功')
        }
      })
  }
  const navigate = useNavigate()
  const addBlog = (values: { title: string; way: string }) => {
    axios
      .post('/blog/add', {
        ...values,
        status,
        content: html,
        editContent: text,
        abstract: getAbstract()
      })
      .then(res => {
        if (res.data.error === -1) {
          message.success('博客添加成功')
          navigate('/index/blog')
        }
      })
  }
  useImperativeHandle(ref, () => ({
    // changeVal 就是暴露给父组件的方法
    onFill
  }))
  const [abstract, setAbstract] = useState('')
  const getAbstract = () => {
    const div = document.createElement('div')
    div.innerHTML = html
    return div.innerText.substring(0, 30) + '...'
  }

  const onFill = (title: string, way: string) => {
    form.setFieldsValue({
      title,
      way
    })
    forceUpdate({})
  }
  return (
    <Form form={form} name="horizontal_login" layout="inline" onFinish={onFinish}>
      <Form.Item label="标题" name="title" rules={[{ required: true, message: '请输入标题!' }]}>
        <Input placeholder="请输入标题" />
      </Form.Item>
      <Form.Item label="方向" name="way" rules={[{ required: true, message: '请输入密码!' }]}>
        <Input placeholder="请输入方向" />
      </Form.Item>

      <Form.Item shouldUpdate>
        {() => (
          <Button
            type="primary"
            htmlType="submit"
            disabled={!form.isFieldsTouched(true) || !!form.getFieldsError().filter(({ errors }) => errors.length).length}
          >
            保存
          </Button>
        )}
      </Form.Item>
    </Form>
  )
}

export default forwardRef(HeaderForm)
